package inno.specificSelection;

import inno.treeRepro.Chromosome;
import inno.treeRepro.ChromosomeComparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class RankSelection implements Selection{

	@Override
	public ArrayList<Chromosome> doSelection(ArrayList<Chromosome> population) {
		
		ArrayList<Chromosome> ans = new ArrayList<Chromosome>();
		
		Collections.sort(population, new ChromosomeComparator());
		
		int sum = 0;
		for (int i=0;i<population.size();i++){
			sum+=i;
		}
		Random rand = new Random();	
		
		// choose two chromos randomicly
		int randSum = rand.nextInt(sum);
		int i = 0;
		
		while (randSum>0){
			randSum-=i;
			++i;
		}
		if (population.size()==i){
			--i;
		}
		ans.add(new Chromosome(population.get(i)));
		
		randSum = rand.nextInt(sum);
		i = 0;
		
		while (randSum>0){
			randSum-=i;
			++i;
		}
		
		if (population.size()==i){
			--i;
		}
		ans.add(new Chromosome(population.get(i)));
		
		return ans;
	}
	

}
